/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */
package be.destin.skos.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;

import be.destin.util.Util;

public class NoXmlDeclarationFileOutputStream extends FileOutputStream {

	/** log4j category */
	static Logger log = Logger.getLogger(NoXmlDeclarationFileOutputStream.class);

	boolean removeXmlDeclaration = false;
	
	public NoXmlDeclarationFileOutputStream(String name)
			throws FileNotFoundException {
		super(name);
		// TODO Auto-generated constructor stub
	}

	/*
	 * Writes len bytes from the specified byte array 
	 */
	public void write(byte[] b,
			int off,
			int len)
	throws IOException {
		if (removeXmlDeclaration && off==0 && len > XMLUtil.begXmlDecl.length) {
			boolean eq = true;
			for (int i=0; i<XMLUtil.begXmlDecl.length; i++) {
				if (b[i]!=XMLUtil.begXmlDecl[i]) {
					eq = false;
					break;
				}
			}
			if ( eq ) {
				int ps = Util.searchBuffer(b,len,XMLUtil.endXmlDecl,/*off+*/XMLUtil.begXmlDecl.length);
				if (ps >= 0) {
					off = ps+XMLUtil.endXmlDecl.length;
					len = len - off;
				}
			}
		}
		super.write(b,off,len);
	}

	public boolean isRemoveXmlDeclaration() {
		return removeXmlDeclaration;
	}

	public void setRemoveXmlDeclaration(boolean removeXmlDeclaration) {
		this.removeXmlDeclaration = removeXmlDeclaration;
	}
}
